package com.euc.springbootframework.util;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by WUNE on 5/7/2018.
 */
public class FreeMarkerUtils {
    private static Logger logger = LoggerFactory.getLogger("auth");
    private static Map<String,Template> templateMap = new HashMap<String,Template>();
    private static Configuration templateconfig;

    static
    {
        templateconfig = new Configuration(Configuration.VERSION_2_3_23);
        templateconfig.setTemplateLoader(new ClassTemplateLoader(FreeMarkerUtils.class,"/"));
        templateconfig.setTemplateUpdateDelayMilliseconds(0);
        templateconfig.setDefaultEncoding("utf-8");
    }

    public static String renderString(String key,String expression,Map<String,?> params) throws Exception{
        Template tl = new Template(key, new StringReader(expression),templateconfig);
        StringWriter sw = new StringWriter();
        try {
            tl.process(params, sw);
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("templateException.",e);
        }finally {
            sw.close();
        }
        return sw.toString();
    }

    public static String renderString(String ftlPath,Map params) throws Exception {
        StringWriter sw = new StringWriter();
        Template tl = templateconfig.getTemplate(ftlPath);
        tl.process(params, sw);
        return sw.toString();
    }

    public static String renderString(Template template,Map params) throws Exception {
        StringWriter sw = new StringWriter();
        template.process(params, sw);
        return sw.toString();
    }

    public static String renderString(Template template,Object object) throws Exception{
        StringWriter sw = new StringWriter();
        template.process(object, sw);
        return sw.toString();
    }


    public static String renderString(String ftlPath,Map params,boolean cache) throws Exception {
        Template template = null;
        if(cache && templateMap.containsKey(ftlPath)){
            template = templateMap.get(ftlPath);
        }else{
            template = templateconfig.getTemplate(ftlPath);
            if(cache){
                templateMap.put(ftlPath, template);
            }
        }
        return renderString(template, params);
    }

    public static String renderFromString(String templateContent, Map params) throws Exception {
        StringWriter sw = new StringWriter();
        Template template = new Template("__template__", templateContent, templateconfig);
        return renderString(template, params);
    }
}
